import { useState } from 'react'
import type { FC } from 'react'

import type { TodoItem } from '../todos'

type IProps = {
  todoList: TodoItem[]
  changeCheckbox: (id: number) => void
  removeTodo: (id: number) => void
  updateTodoItem: (id: number, content: string) => void
}

export const TodoContent: FC<IProps> = (props) => {
  const { todoList, changeCheckbox, removeTodo, updateTodoItem } = props
  const [checkId, setCheckId] = useState(-1)
  const [toduContent, setToduContent] = useState('')

  const onClickTodo = (id: number, content: string) => {
    setCheckId(id)
    setToduContent(content)
  }

  const updateTodo = (e: any) => {
    setToduContent(e.target.value)
  }

  const onBlur = () => {
    updateTodoItem(checkId, toduContent)
    setCheckId(-1)
  }

  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" />
      <label htmlFor="toggle-all">Mark all as complete</label>
      <ul className="todo-list">
        {todoList.map((item) => (
          <li
            key={item.id}
            className={[item.done ? 'completed' : '', checkId === item.id ? 'editing' : ''].join(
              ' '
            )}
          >
            <div className="view">
              <input
                className="toggle"
                type="checkbox"
                checked={item.done}
                onChange={() => changeCheckbox(item.id)}
              />
              <label onDoubleClick={() => onClickTodo(item.id, item.content)}>{item.content}</label>
              <button className="destroy" onClick={() => removeTodo(item.id)} />
            </div>
            <input
              onChange={(e) => updateTodo(e)}
              onBlur={onBlur}
              className="edit"
              value={toduContent}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}
